<?php
namespace app\shops\controller;


use think\Db;
use think\session;
use think\Model;
use think\response\Json;
/**
 * 课程排班管理
 */
class CourseArrange extends Base
{
    /**
     * @throws
     * 课程排班列表
     * @return [type] [description]
     */
    public function index()
    {
        //拿到该课程id,展示该课程排班的情况
        $course_id = input('course_id');

        // 获取配置信息
        $conf = config();
        // 分页信息
        $pageSize   = input('limit')    ? input('limit')    : $conf['paginate']['list_rows'];

        //取出相关数据
        $list = Db('course_time')->alias('ct')
            ->join('course c','c.id=ct.course_id')
            ->join('teacher t','ct.teacher_id=t.teacher_id')
            ->field('ct.id as course_time_id, ct.week_day, ct.period_id, ct.class_id, ct.is_del, c.id as course_id, c.course_name, t.teacher_id, t.teacher_name')
            ->where('c.shop_id',$this->shop_id)->where('ct.course_id',$course_id)->order("ct.id desc")->paginate($pageSize);

        //对象转数组
        $list_to_arr = $list->toArray();

        //处理星期 时段 班级数据
        $week_arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];

        if ($list_to_arr['total']){
            foreach ($list_to_arr['data'] as $key=>$val){
                $new_list[$key]   = $val;
                $new_list[$key]['week_day']=$week_arr[$val['week_day']];
                $period = Db('period')->where('id',$val['period_id'])->find();
                $new_list[$key]['time'] = $period['start_hour'].":".$period['start_minute']."~".$period['end_hour'].":".$period['end_minute'];
                $new_list[$key]['class_name'] = Db('classes')->where('id',$val['class_id'])->value('class_name');
            }
        }

        $this->assign([
            'total'         => $list_to_arr['total'],
            'page'          => $list->render(),
            'new_list'      => $new_list,
            'course_id'     => $course_id
        ]);

        return $this->fetch();

    }

    /**
     * 初次添加排班
     */
    public function add()
    {

        //拿到课程id和具体门店id,为该课程排班
        $course_id = input('course_id');
        $store_id = input('store_id');

        // 新增排课内容
        if(request()->isAjax()) {

            $course_id             = input('course_id');
            $data['arrange_time']  = input('arrange_time');

            //处理数据，把json字符串转数组
            $data['arrange_time']   = json_decode($data['arrange_time'], true);

            Db::startTrans();
            try{
                //数据处理，分割星期 时间段 班级
                foreach ($data['arrange_time'] as $k=>$v){
                    $arr = explode('&',$v);
                    $week_data['week_day']      = $arr[0];
                    $week_data['period_id']     = $arr[1];
                    $week_data['class_id']      = $arr[2];
                    $week_data['teacher_id']    = $arr[3];
                    $week_data['course_id']     = $course_id;
                    Db('course_time')->insert($week_data);
                }
                //修改course表中的是否排班状态
                Db('course')->where('id',$course_id)->setField(['is_arrange'=>1]);
                Db::commit();
            }catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('网络异常');
            }
            $this->success('保存成功');
        }

        //拿到该课程名称
        $courses_info = Db("course")->where('id',$course_id)->field('id as course_id, course_name')->find();

        //拿到该门店下的所有班级
        $classes_list = Db('classes')->where('shop_id',$this->shop_id)->where('store_id',$store_id)->field('id as class_id, class_name')->where('status',0)->select();

        //该数组展示星期
        $week_arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];

        // 列表显示所有排课时段
        $period_list = Db("period")->where('shop_id',$this->shop_id)->where('is_show',1)->order("start_hour asc")->select();

        // 排课时段数据处理(如08:00~09:30)
        if ($period_list){
            foreach ($period_list as $k=>$v){
                $period_list[$k]['time']   = $v['start_hour'].":".$v['start_minute']."~".$v['end_hour'].":".$v['end_minute'];
            }
        }

        //拿到教师姓名
        $teacher_list = Db('teacher')->where('store_id',$store_id)->field('teacher_id, teacher_name')->select();

        $this->assign([
            'courses_info'  => $courses_info,
            'classes_list'  => $classes_list,
            'week_arr'      => $week_arr,
            'period_list'   => $period_list,
            'teacher_list'  => $teacher_list
        ]);

        return $this->fetch();
    }


    /**
     * 首次添加的冲突检测
     */
    public function collision_detection(){

        $arrange_item  = input('arrange_item');
        $arrange_item2 = input('arrange_item2');

        //当点击添加时，拿到传过来的班级、星期、时段去数据库找，若没有找到，即该课程可以去使用这个班级
        $arrange_item  = explode("&", $arrange_item);
        $ret = Db('course_time')->where('class_id',$arrange_item[2])
            ->where('week_day',$arrange_item[0])
            ->where('period_id',$arrange_item[1])
            ->where('is_del',0)->value('id');
        //当点击添加时，拿到传过来的班级、星期、教师去数据库找，若没有找到，即该教师安排授课
        $arrange_item2  = explode("&", $arrange_item2);
        $ret2 = Db('course_time')->where('teacher_id',$arrange_item2[2])
            ->where('week_day',$arrange_item2[0])
            ->where('period_id',$arrange_item2[1])
            ->where('is_del',0)->value('id');

        if (!isset($ret)&&!isset($ret2)){
            $this->success();
        }else{
            if (isset($ret)){
                $this->error('该时间段班级已被占用，请另选~');
            }else{
                $this->error('该时间段该教师已有课，请另选~');
            }

        }

    }



    /**
     * @throws
     * 编辑排班
     */
    public function edit()
    {

        $course_time_id  = input('course_time_id');
        $course_id       = input('course_id');

        // 修改数据
        if(request()->isAjax()){

            //只修改教师
            if(input('teacher_id')){
                $re1 = Db::name('course_time')->where('teacher_id',input('teacher_id'))->where('week_day',input('week_day'))
                    ->where('period_id',input('period_id'))->find();
                if ($re1==''){
                    $re = Db::name('course_time')->where('id',input('course_time_id'))->update(['teacher_id'=>input('teacher_id')]);
                    if ($re){
                        $this->success('编辑成功',"",input('course_id'));
                    }else{
                        $this->error('网络异常');
                    }
                }else{
                    $this->error('该教师已有课~');
                }

            }
            //跳转页面使用要course_id
            $course_time_id  = input('course_time_id');
            $course_id       = input('course_id');
            $data['arrange_time'] = input('arrange_time');

            //处理数据，把json字符串转数组
            $data['arrange_time'] = json_decode($data['arrange_time'], true);

            //数据处理，分割星期 时间段 班级
            $arr = explode('&',$data['arrange_time']);
            $week_data['week_day']      = $arr[0];
            $week_data['period_id']     = $arr[1];
            $week_data['class_id']      = $arr[2];
            $week_data['teacher_id']    = $arr[3];

            $res = Db('course_time')->where('id',$course_time_id)->update($week_data);
            if ($res){
                $this->success('编辑成功',"",$course_id);
            }else{
                $this->error('网络异常');
            }

        }


        //拿到该数据
        $week_info = Db('course_time')->alias('ct')->join('classes c','ct.class_id=c.id')->where('ct.id',$course_time_id)
            ->join('teacher t','ct.teacher_id=t.teacher_id')
            ->field('ct.week_day, ct.period_id, ct.class_id, c.class_name, c.store_id, t.teacher_id, t.teacher_name')->find();

        //所要展示的全部星期
        $week_arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
        //拿到该条数据的星期

        $week_info['week_day']=$week_arr[$week_info['week_day']];

        //拿到该条数据的时段
        $period_info = Db('period')->where('id',$week_info['period_id'])->find();
        $period_info['time'] = $period_info['start_hour'].":".$period_info['start_minute']."~".$period_info['end_hour'].":".$period_info['end_minute'];

        //所要展示的全部时段
        $period_list = Db('period')->field('id as period_id, start_hour, start_minute, end_hour, end_minute')->order('start_hour asc')->select();
        foreach ($period_list as $k=>$v){
            $period_list[$k]['time'] = $v['start_hour'].":".$v['start_minute']."~".$v['end_hour'].":".$v['end_minute'];
        }

        //显示该门店下的所有班级
        $classes_list = Db('classes')->where('store_id',$week_info['store_id'])->where('status',0)->field('id as class_id, class_name')->select();

        //拿到教师姓名
        $teacher_list = Db('teacher')->where('store_id',$week_info['store_id'])->field('teacher_id, teacher_name')->select();

        $this->assign([
            'week_info'      => $week_info,
            'week_arr'       => $week_arr,
            'period_info'    => $period_info,
            'period_list'    => $period_list,
            'classes_list'   => $classes_list,
            'teacher_list'   => $teacher_list,
            'course_id'      => $course_id,
            'course_time_id' => $course_time_id
        ]);

        return $this->fetch();
    }



    /**
     * 再次添加以及部分修改时的冲突检测
     */
    public function collision_detection_again(){

        $arrange_item1 = input('arrange_item1');
        $arrange_item1 = explode("&", $arrange_item1);
        $arrange_item2 = input('arrange_item2');
        $arrange_item2 = explode("&", $arrange_item2);

        $arrange_item3 = input('arrange_item3');
        $arrange_item3 = explode("&", $arrange_item3);

        //是否有空闲的班级
        $ret1 = Db('course_time')
            ->where([
                'class_id'    =>  $arrange_item1[2],
                'week_day'    =>  $arrange_item1[0],
                'period_id'   =>  $arrange_item1[1],
                'is_del'      =>  0
            ])->find();

        //该时间段是否已排
        $ret2 = Db('course_time')
            ->where([
                'course_id'  =>  $arrange_item2[2],
                'week_day'   =>  $arrange_item2[0],
                'period_id'  =>  $arrange_item2[1],
                'is_del'     =>  0
            ])->find();

        if (input('arrange_item3')){
            //该时间段该教师是否有课
            $ret3 = Db('course_time')
                ->where([
                    'teacher_id' =>  $arrange_item3[2],
                    'week_day'   =>  $arrange_item3[0],
                    'period_id'  =>  $arrange_item3[1],
                    'is_del'     =>  0
                ])->find();

            if ($ret1==null && $ret2==null && $ret3==null){
                $this->success();
            }else{

                if ($ret1){
                    $this->error('该时间段该班级已被占用，请另选~');
                }elseif ($ret2){
                    $this->error('该时间段已经排课，请另选~');
                }else{
                    $this->error('该时间段该教师已有课，请另选~');
                }

            }
        }else{
            if ($ret1==null && $ret2==null){
                $this->success();
            }else{
                if ($ret1){
                    $this->error('该时间段该班级已被占用，请另选~');
                }else{
                    $this->error('该时间段已经排课，请另选~');
                }

            }
        }

    }

    /**
     * 再次新增课程的排班
     */
    public function add_again()
    {

        $course_id = input('course_id');

        if (request()->isAjax()){

            $course_id       = input('course_id');
            $data['arrange_time'] = input('arrange_time');

            //处理数据，把json字符串转数组
            $data['arrange_time'] = json_decode($data['arrange_time'], true);

            //数据处理，分割星期 时间段 班级
            $arr = explode('&',$data['arrange_time']);
            $week_data['week_day']      = $arr[0];
            $week_data['period_id']     = $arr[1];
            $week_data['class_id']      = $arr[2];
            $week_data['teacher_id']    = $arr[3];
            $week_data['course_id']     = $course_id;

            $res = Db('course_time')->insert($week_data);
            if($res){
                $this->success("添加成功","",$course_id);
            }else{
                $this->error("网络异常");
            }

        }

        $store_id = Db('course')->where('id',$course_id)->value('store_id');
        //该数组展示星期
        $week_arr = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];

        // 列表显示所有排课时段
        $period_list = Db("period")->where('shop_id',$this->shop_id)->where('is_show',1)->order("start_hour asc")->select();

        // 排课时段数据处理
        if ($period_list){
            foreach ($period_list as $k=>$v){
                $period_list[$k]['time']   = $v['start_hour'].":".$v['start_minute']."~".$v['end_hour'].":".$v['end_minute'];
            }
        }

        //列表显示所有同个门店下的班级名称
        $class_list = Db("classes")->where('store_id',$store_id)->where('status',0)->field('id as class_id, class_name')->order("id desc")->select();

        //列表显示所有同个门店下的教师
        $teacher_list = Db("teacher")->where('store_id',$store_id)->field('teacher_id, teacher_name')->select();

        $this->assign([
            'week_arr'     => $week_arr,
            'period_list'  => $period_list,
            'class_list'   => $class_list,
            'teacher_list' => $teacher_list,
            'course_id'    => $course_id
        ]);

        return $this->fetch();
    }


    /**
     * 排课的状态（开课/闭课）
     */
    public function is_arrange(){

        if (request()->isAjax()){

            $course_time_id   = input('course_time_id');
            $is_del           = input('is_del');
            $course_id        = input('course_id');

            // 修改排课状态
            $res = Db('course_time')->where('course_id',$course_id)->where('id', $course_time_id)->update(['is_del' => $is_del]);

            if($res){
                $this->success("操作成功","",$course_id);
            }else{
                $this->error("网络异常");
            }
        }
    }


}
